<?php

namespace zhtfrontend\controllers;

use common\components\extenders\AjaxObject;
use common\components\helpers\Fun;
use common\components\services\customer\Account;
use common\components\services\orders\Oper;
use common\components\services\orders\ZhtOper;
use common\models\datas\Customer;
use common\models\datas\AccountRecord;
use common\models\datas\Student;
use doumiaoduo\buildform\BuildForm;
use moonland\phpexcel\Excel;
use yii\helpers\Html;
use zhtfrontend\components\helpers\Funs;
use zhtfrontend\components\services\commission\MechanicCommission;
use zhtfrontend\models\datas\ArtTeaching;
use zhtfrontend\models\datas\ClassLesson;
use zhtfrontend\models\datas\ClassManage;
use zhtfrontend\models\datas\ClassManageGoods;
use zhtfrontend\models\datas\ClassStudent;
use common\models\datas\DepositLog;
use zhtfrontend\models\datas\Goods;
use zhtfrontend\models\datas\GoodsAttr;
use zhtfrontend\models\datas\LessonStudent;
use zhtfrontend\models\datas\Mechanic;
use zhtfrontend\models\datas\Orders;
use zhtfrontend\models\datas\OrdersAddress;
use zhtfrontend\models\datas\OrdersItems;
use zhtfrontend\models\datas\OrdersItemsRelation;
use zhtfrontend\models\datas\OrdersLog;
use zhtfrontend\models\datas\OrdersType;
use yii\base\Exception;
use zhtfrontend\models\datas\StudentCheck;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\data\Pagination;
use yii\helpers\Json;
use yii\helpers\ArrayHelper;

class OrdersController extends \zhtfrontend\components\bases\BaseController
{

    public function actionIndex()
    {
        $mid = Fun::getMechanicIds();
        $param['searchData'] = \Yii::$app->request->get();
            $pageSize = isset($param['pageSize']) ? $param['pageSize'] : 12;
            $data = Orders::find()->where(['type_id'=>1])->orderBy('id DESC');
            if (!empty($param['searchData'])) {
                $search_data = array_filter($param['searchData']);
                if (!empty($search_data['year']) && !empty($search_data['mouth'])) {
                    if ($search_data['types'] == 2) {
                        $time = $search_data['year'] . "-" . $search_data['mouth'];
                        $end = Fun::getCurMonthLastDay($time);
                        $data->andWhere(['<=', 'created_at', $end]);
                    } else {
                        $time = $search_data['year'] . "-" . $search_data['mouth'];
                        $start = Fun::getCurMonthFirstDay($time);
                        $end = Fun::getCurMonthLastDay($time);
                        $data->andWhere(['between', 'created_at', $start, $end]);
                    }
                }
//                else{
//                    $timestamp=strtotime('-1 month');
//                    $time = date('Y-m-01',$timestamp);
//                    //$start = Fun::getCurMonthFirstDay($time);
//                    $end = Fun::getCurMonthLastDay($time);
//                    $data->andWhere(['<=', 'created_at', $end]);
//                }

                if (!empty($search_data['name'])) {
                    $customer_ids = Customer::find()->select('id')->where(['like', 'name', $search_data['name']])->andWhere(['site_id' => Fun::getSiteId()])->column();
                    $data->andWhere(['customer_id' => $customer_ids]);
                }
                if (!empty($search_data['mobile'])) {
                    $data->andWhere(['like', 'telephone', $search_data['mobile']]);
                }
                if (!empty($search_data['sn'])) {
                    $data->andWhere(['like', 'sn', $search_data['sn']]);
                }
                if (!empty($search_data['mechanic_id'])) {
//                    $orders_ids = OrdersItems::find()->select('orders_id')->where(['mechanic_id' => $search_data['mechanic_id']])->column();
                    $data->andWhere(['machanic_id' => $search_data['mechanic_id']]);
                }
            }
            if ($mid) {
//                $oids = OrdersItems::find()->select('orders_id')->where(['mechanic_id' => $mid])->column();
                $data->andWhere(['mechanic_id' => $mid]);
            }
            if (isset(\Yii::$app->user->identity) && \Yii::$app->user->identity->role == 'class_director') {
                $DirectorMechanicIds = Fun::getDirectorMechanicIds();
//                $oids = OrdersItems::find()->select('orders_id')->where(['mechanic_id' => $DirectorMechanicIds])->column();
                $data->andWhere(['mechanic_id' => $DirectorMechanicIds]);
            }
            $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $pageSize]);
            isset($param['page']) ? $pages->page = $param['page'] - 1 : 0;
            $model = $data->offset($pages->offset)->limit($pages->limit)->all();
            $arr = Fun::asArray($model, ['customer_name', 'status_name', 'operate', 'appointment_name', 'ship_status_name', 'pay_status_name', 'payment_name']);
            foreach ($arr as $key => $val) {
                $arr[$key]['deposit'] = '无需交保证金'; //无需交保证金
                if ($val['order_type'] == 'appointment') {
                    $items = OrdersItems::find()->where(['orders_id' => $val['id'], 'teach_type' => 1])->one();
                    if ($items != null) {
                        $goods = Goods::findOne($items->goods_id);
                        if ($goods != null) {
                            if ($goods->deposit > $val['cash_money']) {
                                $deposit = DepositLog::find()->where(['orders_id' => $val['id'], 'customer_id' => $val['customer_id'], 'site_id' => Fun::getSiteId()])->one();
                                if ($deposit == null) {
                                    $arr[$key]['deposit'] = '未交保证金';
                                } else {
                                    $arr[$key]['deposit'] = '已交保证金';
                                }
                            }
                        }
                    }
                }
            }

//        $mechanic_ids = OrdersItems::find()->select('mechanic_id')->joinWith('orderss')->groupBy('mechanic_id')->column();
        $mechanic_ids = Orders::find()->select('mechanic_id')->groupBy('mechanic_id')->column();
        $mechanicModel = Mechanic::find()->where(['id' => $mechanic_ids])->orderBy('id DESC');
        if ($mid) {
            $mechanicModel->where(['id' => $mid]);
        }
        $mechanic = $mechanicModel->asArray()->all();
        $data_mechanic = ArrayHelper::map($mechanic, 'id', 'name');
        $data_mechanic[0] = '请选择';
        return $this->render('index', ['mechanic' => $data_mechanic,'data'=>$arr,'pages'=>$pages]);
    }

    /**
     *  详情
     */
    public function actionDetails()
    {
        $id = \Yii::$app->request->get('id');
        $model = Orders::findOne($id);
        if ($model == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $is_start = 0;
        $OrdersItems = OrdersItems::find()->where(['orders_id' => $id])->all();
        $itemrelaction = OrdersItemsRelation::find()->where(['orders_id'=>$id])->one();
        $orderitems = Fun::asArray($OrdersItems, ['status_name', 'type_name', 'goods_type_id', 'mechanic_name', 'total', 'student_name', 'class_status', 'check_number', 'is_start', 'is_was']);
        foreach ($orderitems as $k => $item) {
            $orderitems[$k]['view'] = '';
            $orderitems[$k]['is_return'] = 1;
            $orderitems[$k]['check_number'] = 0;
            if ($item['teach_type'] == 1) {
                $classGoods = ClassManageGoods::find()->where(['goods_id'=>$item['goods_id']])->one();
                $manage = ClassManage::findOne($classGoods->class_id);
                $class_count = isset($itemrelaction->lesson) ? $itemrelaction->lesson : 0;
                $classStudent = ClassStudent::find()->where(['order_sales_id'=>$item['id']])->one();
                if ($classStudent != null && $classStudent->status == 1) {
                    $now = time();
                    $count = ClassLesson::find()->where(['class_id' => $manage->class_id])->andWhere(['between','class_date',$classStudent->start_time,$now])->count();
                    $orderitems[$k]['check_number'] = $count;
                    if ($count > $class_count/3) {
                        $orderitems[$k]['is_return'] = 0;
                    }
                }
                $orderitems[$k]['class_count'] = $class_count;
            } else {
                $art = ArtTeaching::findOne($item['goods_id']);
                $orderitems[$k]['class_count'] = isset($itemrelaction->art_lesson) ? $itemrelaction->art_lesson : 0;
                $type = '益智';
                if ($art->type == 2) {
                    $type = '音乐';
                } elseif ($art->type == 3) {
                    $type = '形体';
                }
                $orderitems[$k]['type_name'] = $type;
                $orderitems[$k]['view'] = $orderitems[$k]['view'] = Html::a('查看', 'javascript:;', ['rel' => 'dialog-show-iframe', 'data-name' => '查看', 'data-size' => '800*500', 'data-url' => Fun::url(['goodsskill/viewgroup', 'id' => $item['goods_id']]), 'class' => 'yx-batch-settlement yx-radius2']);
            }
        }
        $orders = Fun::asArray([$model], ['customer_created_at', 'card_id', 'customer_name', 'status_name', 'pay_status_name', 'ship_status_name', 'appointment_name', 'payment_name', 'appointment_name']);
        $addr = OrdersAddress::find()->where(['orders_id' => $id])->one();
        return $this->render('details', ['order' => $orders, 'orderitem' => $orderitems, 'addr' => $addr, 'is_start' => $is_start]);
    }

    //设置可购买此类型课程
    public function actionInvalid()
    {
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model = Orders::findOne($id);
        if ($model == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '订单不存在'));
        }
        if (!in_array($model->status, [4, 5])) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '此订单不可以设置'));
        }
        $model->is_invalid = 1;
        if ($model->save(false)) {
            $log_text = '设置此订单为可购买同分类课程';
            $logs = ['orders_id' => $id, 'status' => $model->status, 'result' => 'SUCCESS', 'log_text' => $log_text];
            Oper::addOrderLog($logs);//添加订单记录
            return $this->redirectMessage(\Yii::t('zhtfrontend', '操作成功'), Fun::url(['orders/details', 'id' => $id]));
        } else {
            return $this->redirectMessage('操作失败', Fun::url(['orders/details', 'id' => $id]));
        }
    }

    public function actionStatus()
    {
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $status = \Yii::$app->request->get('status');
        switch ($status) {
            case 1:
                $log_text = '订单已确认';
                $log_status = 1;
                break;
            case 3:
                $this->removeStudent($id, 5);
                $log_text = '无效订单';
                $log_status = 4;
                break;
            case 5:
                $log_text = '订单完成';
                $log_status = 5;
                break;
        }
        $model = Orders::findOne($id);
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $model->status = $status;
            $model->save(false);
            $logs = ['orders_id' => $id, 'status' => $log_status, 'result' => 'SUCCESS', 'log_text' => $log_text];
            Oper::addOrderLog($logs);//添加订单记录
            $transaction->commit();
            return $this->redirectMessage(\Yii::t('zhtfrontend', '操作成功'), Fun::url(['orders/details', 'id' => $id]));

        } catch (\Exception $e) {
            $transaction->rollBack();
            return $this->redirectMessage('操作失败', Fun::url(['orders/details', 'id' => $id]));
        }

    }

    /**
     * 管理员设置支付
     * @return object|string
     * @throws NotFoundHttpException
     * @throws \yii\base\ErrorException
     * @throws \yii\db\Exception
     */

    public function actionPaystatus()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model = Orders::findOne($id);
        if ($model == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $customer = Customer::findOne($model->customer_id);

        $student = Student::find()->where(['customer_id' => $customer->id])->one();
        if ($customer->scholarship_available <= $model->final_amount) {
            $model->scholarship_money = $customer->scholarship_available;
            $model->cash_money = $model->final_amount - $customer->scholarship_available;
        } else {
            $model->scholarship_money = $model->final_amount;
            $model->cash_money = 0;
        }
        //判断订单中是否存在课程
        $order_type = OrdersType::find()->where(['orders_id' => $model->id])->all();
        foreach ($order_type as $type) {
            if ($type->type_id == 1 && $model->order_type == 'appointment') {
                if ($customer->scholarship_available <= $type->amount) {
                    $model->scholarship_money = $customer->scholarship_available;
                } else {
                    $model->scholarship_money = $type->amount;
                }
                break;
            }
        }
        $model->cash_money = $model->final_amount - $model->scholarship_money;
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {

            $aount = (int)$model->scholarship_money + (int)$model->cash_money;
            if ($aount < $model->final_amount) {
                throw new NotFoundHttpException(\Yii::t('zhtfrontend', '余额不足请先充值！'));
            }
            $transaction = \Yii::$app->db->beginTransaction();
            try {
                //修改订单支付状态及付款时间
                $model->pay_status = 1;
                $model->pay_time = time();
                $model->save(false);
                //减少奖学金和余额
                $option = [
                    'customer_id' => $model->customer_id,
                    'account' => $model->cash_money,
                    'scholarship_available' => $model->scholarship_money,
                    'orders_id' => $id,
                    'state' => 5,
                    'note' => '订单消费资金'
                ];
                Account::CustomerAccountReduce($option);//操作用户资金
                foreach ($order_type as $type) {
                    //如果是课程设置订单商品付款额度比例

                    $items = OrdersItems::find()->where(['orders_type_id' => $type->id])->all();
                    foreach ($items as $item) {
                        if ($type->type_id == 1) {
                            $proportion = $item->amount / $type->amount;
                            $item->scholarship_money = $model->scholarship_money * $proportion;
                            $item->cash_money = $model->cash_money * $proportion;
                            $item->save(false);
                            //如果是课程把学员放入班级中去
                            $classmanager = ClassManage::find()->where(['is_old' => 0, 'associate_id' => $item->goods_id])->one();
                            $ClassStudent = new ClassStudent();
                            $ClassStudent->class_manage_id = $classmanager->class_id;
                            $ClassStudent->order_sales_id = $item->id;
                            $ClassStudent->student_id = $student->id;
                            $ClassStudent->status = 0;
                            $ClassStudent->start_time = 0;
                            $ClassStudent->end_time = 0;
                            $ClassStudent->is_deposit = 0;
                            $ClassStudent->save(false);
                        } else {
                            $item->cash_money = $model->cash_money * $proportion;
                            $item->save(false);
                        }
                    }
                }
                //订单操作记录
                $option = ['orders_id' => $id, 'status' => 2, 'result' => 'SUCCESS', 'log_text' => '管理员操作支付'];
                Oper::addOrderLog($option);
                $transaction->commit();
                return $this->redirectMessage(\Yii::t('zhtfrontend', '支付成功'), Fun::url(['orders/details', 'id' => $id]));
            } catch (\Exception $e) {
                $transaction->rollBack();
                return $this->redirectMessage('支付失败', Fun::url(['orders/details', 'id' => $id]));
            }
        }
        return $this->render('paystatus', ['model' => $model, 'customer' => $customer]);
    }

    /*
     *  退课
     */
    public function actionRefund()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model = OrdersItems::findOne($id);
        if ($model == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $orderMmodel = Orders::findOne($model->orders_id);
        if ($model->status == 3 || $orderMmodel->pay_status == 0) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '此课程已退款或未付款'));
        }
        $goodsAttr = Funs::getGoodsAttr($model->goods_id);
        $class_count = isset($goodsAttr['class_count']) ? (int)$goodsAttr['class_count'] : 0;
        $itemRelation = OrdersItemsRelation::find()->where(['orders_id'=>$orderMmodel->id])->one();
        $lesson_price = $model->price;
        if($itemRelation != null){
            $class_count = $itemRelation->lesson;
            $lesson_price = $itemRelation->lesson_price;
        }
        $classGoods = ClassManageGoods::find()->where(['goods_id'=>$model->goods_id])->one();
        $classmanage = ClassManage::findOne($classGoods->class_id);
        $now = time();
        $count = 0 ;
        $classstudent = ClassStudent::find()->where(['class_manage_id'=>$classmanage->class_id,'order_sales_id'=>$model->id])->one();
        if($classstudent != null && $classstudent->start_time > 0) {
            $count = ClassLesson::find()->where(['class_id' => $classmanage['class_id']])->andWhere(['between', 'class_date', $classstudent->start_time, $now])->count();
        }

        if ($count > $class_count/3) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '上课次数已超出退课限制'));
        }

        //查找艺教学课程
        $art_orders_items = OrdersItems::find()->where(['orders_id' => $model->orders_id, 'teach_type' => 2])->one();
        $deduction_art = 0;
        if ($art_orders_items != null) {
            $result_art = $this->getArtclasscount($art_orders_items->id);
            $scholarship_money = $art_orders_items->scholarship_money; //使用奖学金
            $cash_money = $art_orders_items->cash_money; //使用现金

            $artOneLessonPrice = $itemRelation->art_lesson_price/$itemRelation->art_lesson;
            //如果已上课
            if ($result_art['okcount'] > 0) {
                $deduction_art = $artOneLessonPrice*$result_art['okcount'];
            }
             if($cash_money > 0){
                 $cash_money = ($cash_money-$deduction_art > 0)?$cash_money-$deduction_art:0;
             }
            if($scholarship_money > 0){
                if($cash_money < $deduction_art ){
                    $scholarship_money = $scholarship_money - ($deduction_art-$cash_money);
                }
            }

            $art_class_count = $result_art['modelArt']->class_count;
            if($itemRelation != null){
                $art_class_count = $itemRelation->art_lesson;
            }
            $arr_art = [
                'name' => $art_orders_items->name,
                'class_count' =>$art_class_count,
                'ok_class_count' => $result_art['okcount'],
                'scholarship_money' => $scholarship_money, //需退奖学金
                'money' => $cash_money, //需退的余额，
            ];
        } else {
            $arr_art = [];
        }
        $result = $this->getClasscount($id);
        $scholarship_money = $model->scholarship_money;
        $cash_money = $model->cash_money;
        $GoodsOneLessonPrice = $lesson_price/$class_count;
        $deduction = 0;
        //如果已上课
//            $scholarship_proportion = $model->scholarship_money / $result['count']; //红包每课次的金额
//            $cash_proportion = $model->cash_money / $result['count']; //奖学金每课次的金额
//            $scholarship_money = floor(($result['count'] - $result['okcount']) * $scholarship_proportion);
//            $cash_money = floor(($result['count'] - $result['okcount']) * $cash_proportion);
        $deduction = $GoodsOneLessonPrice*$result['okcount']; //已上课的总价格
        if($cash_money > 0){
            $cash_money = ($cash_money-$deduction > 0)?$cash_money-$deduction:0;
        }
        if($scholarship_money > 0) {
            if ($cash_money < $deduction) {
                $scholarship_money = $scholarship_money - ($deduction - $cash_money);
            }
        }
        $arr = [
            'name' => $model->name,
            'class_count' => $class_count,
            'ok_class_count' => $result['okcount'],
            'scholarship_money' => $scholarship_money, //需退奖学金
            'money' => $cash_money, //需退的余额，
        ];


        if (\Yii::$app->request->post() && \Yii::$app->request->isPost) {
            $post = \Yii::$app->request->post();
            $scholarship_money = isset($post['scholarship_money'])?(float)$post['scholarship_money']:0;
            $money = isset($post['money'])?(float)$post['money']:0;
            $model->status = 3;
//            if ($result['okcount'] > 0) {
//                $model->status = 4;
//            }
            $model->actual_scholarship_money -= $scholarship_money;
            $model->actual_cash_money -= $money;
            $model->save(false);
            $goodsRow = Goods::findOne($model->goods_id);
            if($goodsRow != null){
                $goodsRow->store += 1;
                $goodsRow->save(false);
            }

            $classstudent = ClassStudent::find()->where(['order_sales_id' => $id, 'student_id' => $model->student_id])->one();
            //class_student修改
            if ($classstudent) {

                //student_check状态修改，已上课不变
                $lesson = 1;
                if($classstudent->status > 0) {
                    $newLessonRow = ClassLesson::find()->where(['class_id' => $classstudent->class_manage_id])->andWhere(['between', 'class_date', $classstudent->start_time, $now])->orderBy('lesson_id DESC')->one();
                    if ($newLessonRow != null) {
                        $nextLesson = ClassLesson::find()->where(['class_id' => $classstudent->class_manage_id])->andWhere(['>', 'lesson_id', $newLessonRow->lesson_id])->orderBy('lesson_id ASC')->one();
                        $lesson = $nextLesson->lesson;
                        $surplusLesson = ClassLesson::find()->select('lesson_id')->where(['class_id' => $classstudent->class_manage_id])->andWhere(['>', 'lesson_id', $newLessonRow->lesson_id])->column();
                        StudentCheck::updateAll(['status' => 3, 'created_at' => time()], ['class_student_id' => $classstudent->id, 'class_lesson_id' => $surplusLesson]);
                        LessonStudent::updateAll(['status' => 3, 'check_time' => time()], ['lesson_id' => $surplusLesson, 'student_id' => $classstudent->student_id]);
                    } else {
                        $surplusLesson = ClassLesson::find()->select('lesson_id')->where(['class_id' => $classstudent->class_manage_id])->column();
                        StudentCheck::updateAll(['status' => 3, 'created_at' => time()], ['class_student_id' => $classstudent->id, 'class_lesson_id' => $surplusLesson]);
                        LessonStudent::updateAll(['status' => 3, 'check_time' => time()], ['student_id' => $classstudent->student_id, 'lesson_id' => $surplusLesson,]);
                    }
                }
                $classstudent->end_time = time();
                $classstudent->status = 4;
                $classstudent->save();

                //预约课程减少机构相应补贴
                if($orderMmodel->order_type == 'appointment'){
                    MechanicCommission::InserRefund($model->goods_id,$lesson);
                }


//                $student_check = StudentCheck::find()->where(['class_student_id' => $classstudent->id])->andWhere(['!=', 'status', 1])->all();
//                foreach ($student_check as $k => $v) {
//                    $v->status = 3;
//                    $v->save(false);
//                    //lesson_student状态修改，已上课不变
//                    $lesson_student = LessonStudent::find()->where(['lesson_id'=>$v->class_lesson_id,'student_id'=>$v->student_id])->one();
//                    $lesson_student->status = 11;
//                    $lesson_student->save(false);
//                }
            }
            $scholarship_money_art = isset($post['scholarship_money_art'])?(float)$post['scholarship_money_art']:0;
            $money_art = isset($post['money_art'])?(float)$post['money_art']:0;
            if ($art_orders_items != null) {
                $art_orders_items->status = 3;
//                if ($result_art['okcount'] > 0) {
//                    $art_orders_items->status = 4;
//                }
                $art_orders_items->actual_scholarship_money -= $scholarship_money_art;
                $art_orders_items->actual_cash_money -= $money_art;
                $art_orders_items->save(false);
                $classstudent_art = ClassStudent::find()->where(['order_sales_id' => $art_orders_items->id, 'student_id' => $art_orders_items->student_id])->one();
                if ($classstudent_art) {
                    $classstudent_art->end_time = time();
                    $classstudent_art->status = 2;
                    $classstudent_art->save();
                    $newLessonRow = ClassLesson::find()->where(['class_id' => $classstudent_art->class_manage_id])->andWhere(['between','class_date',$classstudent_art->start_time,$now])->orderBy('lesson_id DESC')->one();
                    if($newLessonRow != null) {
                        $surplusLesson = ClassLesson::find()->select('lesson_id')->where(['class_id' => $classstudent_art->class_manage_id])->andWhere(['>', 'lesson_id', $newLessonRow->lesson_id])->column();

                        StudentCheck::updateAll(['status' => 3, 'created_at' => time()], ['class_student_id' => $classstudent_art->id, 'class_lesson_id' => $surplusLesson]);
                        LessonStudent::updateAll(['status' => 3, 'check_time' => time()], ['lesson_id' => $surplusLesson, 'student_id' => $classstudent_art->student_id]);
                    }else{
                        $surplusLesson = ClassLesson::find()->select('lesson_id')->where(['class_id' => $classstudent_art->class_manage_id])->column();
                        StudentCheck::updateAll(['status' => 3, 'created_at' => time()], ['class_student_id' => $classstudent_art->id,'class_lesson_id' => $surplusLesson]);
                        LessonStudent::updateAll(['status' => 3, 'check_time' => time()], ['student_id' => $classstudent_art->student_id,'lesson_id' => $surplusLesson,]);
                    }
                }
            }

            $option = [
                'customer_id' => $orderMmodel->customer_id,
                'account' => $money + $money_art,
                'scholarship_available' =>$scholarship_money+ $scholarship_money_art,
                'orders_id' => $orderMmodel->id,
                'state' => 5,
                'note' => '退货退还金额',
                'mode' => 2
            ];

            //print_r($option);die;
            if ($result['okcount'] > 0) {
                $orderMmodel->status = 5;
                //$orderMmodel->ship_status = 3;
                $orderMmodel->pay_status = 4;
            } else {
                $orderMmodel->status = 4;
                //$orderMmodel->ship_status = 5;
                $orderMmodel->pay_status = 5;
            }
            $orderMmodel->final_amount = $orderMmodel->final_amount - ($money + $scholarship_money+$scholarship_money_art+$money_art);
            $orderMmodel->remain_amount = $orderMmodel->remain_amount - ($money + $scholarship_money+$scholarship_money_art+$money_art);
            $orderMmodel->scholarship_money = $orderMmodel->scholarship_money- ($scholarship_money+$scholarship_money_art);
            $orderMmodel->cash_money = $orderMmodel->cash_money- ($money+$money_art);
            $orderMmodel->save(false);

            Account::CustomerAccountIncrease($option);//操作用户资金
            $options = ['orders_id' => $orderMmodel->id, 'status' => 6, 'result' => 'SUCCESS', 'log_text' => '管理员操作退课'];
            ZhtOper::addOrderLog($options);//添加订单记录
            return $this->redirectMessage('退课成功！', Fun::url(['orders/details', 'id' => $orderMmodel->id]));
        }

        return $this->render('refund', ['model' => $model, 'items' => $arr, 'items_art' => $arr_art]);

    }

    //实物退货
    public function actionReceded()
    {
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model = OrdersItems::findOne($id);
        if ($model == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $ordersModel = Orders::findOne($model->orders_id);
        $sevenDay = 24 * 60 * 60 * 7;
        if ((time() - $ordersModel->created_at) > $sevenDay) {
            return $this->redirectMessage('您的商品已经超出退货时间！', Fun::url(['orders/details', 'id' => $ordersModel->id]));
        }
        $model->status = 3;
        $model->actual_scholarship_money -= $model->scholarship_money;
        $model->actual_cash_money -= $model->cash_money;
        if ($model->save(false)) {
            $res = OrdersItems::find()->where(['status' => [1, 4], 'orders_id' => $ordersModel->id])->all();
            if ($res) {
                $ordersModel->status = 5;
                //$ordersModel->ship_status = 3;
                $ordersModel->pay_status = 4;
            } else {
                $ordersModel->status = 4;
                //$ordersModel->ship_status = 5;
                $ordersModel->pay_status = 5;
            }
            $ordersModel->remain_amount -= ($model->scholarship_money + $model->cash_money);
            $ordersModel->save(false);
            $option = [
                'customer_id' => $ordersModel->customer_id,
                'account' => $model->cash_money,
                'scholarship_available' => $model->scholarship_money,
                'orders_id' => $ordersModel->id,
                'state' => 5,
                'note' => '退货退还金额',
                'mode' => 2
            ];
            Account::CustomerAccountIncrease($option);//操作用户资金
            $options = ['orders_id' => $ordersModel->id, 'status' => 6, 'result' => 'SUCCESS', 'log_text' => '管理员操作退货'];
            Oper::addOrderLog($options);//添加订单记录
            return $this->redirectMessage('退货成功！', Fun::url(['orders/details', 'id' => $ordersModel->id]));
        }
    }

    //换货
    public function actionExchange()
    {
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model = OrdersItems::findOne($id);
        if ($model == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $ordersModel = Orders::findOne($model->orders_id);
        $sevenDay = 24 * 60 * 60 * 30;
        if ((time() - $ordersModel->created_at) > $sevenDay) {
            return $this->redirectMessage('您的商品已经超出退货时间！', Fun::url(['orders/details', 'id' => $ordersModel->id]));
        }
        $model->status = 2;
        if ($model->save(false)) {
            $options = ['orders_id' => $ordersModel->id, 'status' => 6, 'result' => 'SUCCESS', 'log_text' => '管理员操作换货'];
            Oper::addOrderLog($options);//添加订单记录
            return $this->redirectMessage('换货成功！', Fun::url(['orders/details', 'id' => $ordersModel->id]));
        }
    }

    /**
     * 取消订单
     */
    public function actionCancel()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model = Orders::findOne($id);
        if ($model == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $is_class = 0;
        $items = OrdersItems::find()->where(['orders_id' => $id])->all();
        foreach ($items as $item) {
            $classstudent = ClassStudent::find()->where(['order_sales_id' => $item->id, 'student_id' => $item->student_id])->one();
            if ($classstudent) {
                $classmanager = ClassManage::findOne($classstudent->class_manage_id);
                if ($classmanager->status == 1) {
                    $is_class += 1;
                }
            }
        }
        if ($is_class > 0 || $model->status == 2 || $model->ship_status == 2 || $model->status == 3) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '此订单已取消或已开课或者是无效订单'));
        }
        if (\Yii::$app->request->post()) {
            $post = \Yii::$app->request->post();
            $is_return = isset($post['is_return']) ? $post['is_return'] : 0;
            if ($is_return == 1) {
                $model->status = 2;
                $model->pay_status = 5;
                $model->updated_at = time();
                $model->save(false);
                $option = [
                    'customer_id' => $model->customer_id,
                    'account' => $model->cash_money,
                    'scholarship_available' => $model->scholarship_money,
                    'orders_id' => $id,
                    'state' => 5,
                    'note' => '取消订单退还金额',
                    'mode' => 2
                ];
                Account::CustomerAccountIncrease($option);//操作用户资金
            } else {
                $model->status = 2;
                $model->updated_at = time();
                $model->save(false);
            }
            $this->removeStudent($id);
            $logs = ['orders_id' => $id, 'status' => 3, 'result' => 'SUCCESS', 'log_text' => '管理员操作取消订单'];
            Oper::addOrderLog($logs);//添加订单记录
            return $this->redirectMessage('取消订单成功！', Fun::url(['orders/details', 'id' => $id]));
        }
        return $this->render('cancel', ['model' => $model]);
    }

    //移除学生所在班级
    public function removeStudent($orders_id, $status = 4)
    {
        $orderType = OrdersType::find()->where(['orders_id' => $orders_id])->all();
        foreach ($orderType as $type) {
            if ($type->type_id == 1) {
                $orderitems = OrdersItems::find()->where(['orders_type_id' => $type->id])->all();
                foreach ($orderitems as $item) {
                    $item->status = $status;
                    $item->save(false);
                    $classstudent = ClassStudent::find()->where(['order_sales_id' => $item->id])->one();
                    if ($classstudent != null)
                        $classstudent->delete();
                }

            }
        }
    }

    /**
     *  交保证金
     */
    public function actionDeposit()
    {
        $orderitem_id = \Yii::$app->request->get('id');
        $items = OrdersItems::findOne($orderitem_id);
        if ($items === null || $items->student_id == 0) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $customer = Customer::findOne($items->orders->customer_id);
        if ($customer === null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '会员信息不存在'));
        }
        $res = DepositLog::find()->where(['status' => 0, 'customer_id' => $customer->id, 'orders_items_id' => $orderitem_id])->one();

        if ($res != null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '保证金已交'));
        }
        $goods = Goods::findOne($items->goods_id);
        $deposit_fee = isset($goods) ? $goods->deposit : 200;
        $model = new AccountRecord();
        $model->scenario = 'cash_back';
        $model->customer_id = $customer->id;
        $form = new EasyuiForm('@app/components/forms/accountrecordchargeForm.php');
        $form->loadModel(['accountrecord' => $model]);
        $form->loadDefaultValues();
        if ($form->loadData(\Yii::$app->request->post()) && $form->validate()) {
            $account = (int)$model->pay_cash + (int)$model->pay_pos + (int)$model->free;
            $customer->deposit = +$account;
            $transaction = \Yii::$app->db->beginTransaction();
            try {
                $customer->save(false);
                $model->cash = $account;
                $model->site_id = Fun::getSiteId();
                $model->user_id = \Yii::$app->user->id;
                $model->created_at = time();
                $model->deposit = $account;
                $model->state = 4;
                $model->order_id = $items->orders_id;
                $model->note = '交保证金';
                $model->save(false);

                $depositLog = new DepositLog();
                $depositLog->customer_id = $customer->id;
                $depositLog->site_id = Fun::getSiteId();
                $depositLog->orders_id = $items->orders_id;
                $depositLog->orders_items_id = $orderitem_id;
                $depositLog->mode = Fun::getSiteMode(Fun::getSiteId());
                $depositLog->money = $account;
                $depositLog->pay_type = 2;
                $depositLog->created_at = time();
                $depositLog->code = isset($items->orders) ? $items->orders->sn : date('YmdHis') . round(10, 99);
                if ($depositLog->save(false)) {
                    $classmanage = ClassManage::find()->where(['associate_id' => $items->goods_id])->one();
                    $classstudent = new ClassStudent();
                    $classstudent->class_manage_id = $classmanage->class_id;
                    $classstudent->order_sales_id = $orderitem_id;
                    $classstudent->student_id = $items->student_id;
                    if ($classmanage->status == 1) {
                        $classstudent->status = 1;
                        $classstudent->start_time = $classmanage->start_time;
                        $classstudent->end_time = $classmanage->end_time;
                    }
                    $classstudent->mode = Fun::getSiteMode(Fun::getSiteId());
                    $classstudent->is_paydeposit = 1;
                    if ($classstudent->save(false)) {
                        if ($classmanage->status == 1) {
                            $student_check = [];
                            $lesson_student = [];
                            $goodsattr = GoodsAttr::find()->where(['goods_id' => $items->goods_id, 'obj_type' => 'class_count'])->one();
                            $count = (int)$goodsattr->value;
                            //插入打卡表/lesson_student
                            for ($i = 1; $i <= $count; $i++) {
                                $class_lesson = ClassLesson::findOne(['class_id' => $classstudent->class_manage_id, 'lesson' => $i]);
                                $student_check[$i]['class_student_id'] = $classstudent->id;
                                $student_check[$i]['order_sales_id'] = $orderitem_id;
                                $student_check[$i]['student_id'] = $items->student_id;
                                $student_check[$i]['status'] = null;
                                $student_check[$i]['created_at'] = null;
                                $student_check[$i]['class_lesson_id'] = $class_lesson->lesson_id;

                                $lesson_student[$i]['lesson_id'] = $class_lesson->lesson_id;
                                $lesson_student[$i]['status'] = 0;
                                $lesson_student[$i]['student_id'] = $items->student_id;
                            }
                            Fun::getSiteDb()->createCommand()->batchInsert('{{%student_check}}', ['class_student_id', 'order_sales_id', 'student_id', 'status', 'created_at', 'class_lesson_id'], $student_check)->execute();
                            Fun::getSiteDb()->createCommand()->batchInsert('{{%lesson_student}}', ['lesson_id', 'status', 'student_id'], $lesson_student)->execute();
                        }
                    }
                }
                $transaction->commit();
                return $this->redirectMessage('交保证金成功', Fun::url(['orders/details', 'id' => $items->orders_id]));
            } catch (\Exception $e) {
                $transaction->rollBack();
                return $this->redirectMessage('交保证金失败', Fun::url(['orders/details', 'id' => $items->orders_id]));
            }
        }
        return $this->render('deposit', ['form' => $form->render(), 'customer' => $customer, 'deposit_fee' => $deposit_fee]);
    }


    /**
     * @param $items_id
     * @return array
     */

    public function getClasscount($items_id)
    {
        $count = 6;
        $orderitem = OrdersItems::findOne($items_id);
        $classstudent = ClassStudent::find()->where(['student_id' => $orderitem->student_id, 'order_sales_id' => $orderitem->id])->one();
        $okCount = 0;
        if (isset($classstudent) && $classstudent->start_time > 0) {
            $now = time();
            $orderTime = $classstudent->start_time;
            $okCount = ClassLesson::find()->where(['class_id' => $classstudent->class_manage_id])->andWhere(['between', 'class_date', $orderTime,$now])->count();
        }
        $row = $orderrelation = OrdersItemsRelation::find()->where(['orders_id'=>$orderitem->orders_id])->one();
        if ($row) {
            $count = $row->lesson;
        }
        return [
            'okcount' => $okCount,
            'count' => $count,
        ];
    }

    /**
     * @param $items_id
     * @return array
     */

    public function getArtclasscount($items_id)
    {
        $count = 0;
        $orderitem = OrdersItems::findOne($items_id);
        $classstudent = ClassStudent::find()->where(['student_id' => $orderitem->student_id, 'order_sales_id' => $orderitem->id])->one();
        $okCount = 0;
        if ($classstudent) {
            $now = time();
            $orderTime = $orderitem->created_at;
            $okCount = ClassLesson::find()->where(['class_id' => $classstudent->class_manage_id])->andWhere(['between', 'class_date',$classstudent->start_time, time()])->count();
        }
        $row = ArtTeaching::findOne($orderitem->goods_id);
        return [
            'okcount' => $okCount,
            'count' => $count,
            'modelArt' => $row
        ];
    }


}